package cn.edu.scau.cmi.ema.controller.rest;

import org.springframework.stereotype.Controller;

import java.util.List;
import java.util.HashSet;
import java.util.Iterator;
import java.util.Set;
import java.io.IOException;

import com.google.gson.Gson;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;


import cn.edu.scau.cmi.ema.base.CmiPagination;
import cn.edu.scau.cmi.ema.service.base.CmiPsonService;
import cn.edu.scau.cmi.ema.base.CmiEmaController;
import cn.edu.scau.cmi.ema.dao.*;
import cn.edu.scau.cmi.ema.domain.*;
import cn.edu.scau.cmi.ema.service.*;

import org.springframework.web.bind.annotation.*;
import javax.servlet.http.HttpServletRequest;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.bind.WebDataBinder;

@Controller("QuantitytypeRestController")
public class QuantitytypeRestController extends CmiEmaController {

	/**
	 * Create a new Quantitytype entity
	 * 
	 */
	@RequestMapping(value = "/newQuantitytype", method = RequestMethod.POST)
	@ResponseBody
	public Object newQuantitytype(@RequestBody Quantitytype quantitytype) {
		quantitytypeService.saveQuantitytype(quantitytype);
		return JSONObject
				.parse(cmiPsonService.toJsonString(quantitytypeDAO.findQuantitytypeByPrimaryKey(quantitytype.getId()), 2));
	}

	@RequestMapping(value = "/restNewQuantitytype", method = RequestMethod.POST)
	@ResponseBody
	public Object restNewQuantitytype(@RequestBody String quantitytypeJson) {
		Quantitytype quantitytype = new Gson().fromJson(quantitytypeJson, Quantitytype.class);
		appendReferences(quantitytype);
		quantitytypeService.saveQuantitytype(quantitytype);
		return JSONObject
				.parse(cmiPsonService.toJsonString(quantitytypeDAO.findQuantitytypeByPrimaryKey(quantitytype.getId()), 2));
	}

	@RequestMapping(value = "/saveQuantitytype", method = RequestMethod.PUT)
	@ResponseBody
	public Quantitytype saveQuantitytype(@RequestBody Quantitytype quantitytype) {
		quantitytypeService.saveQuantitytype(quantitytype);
		return quantitytypeDAO.findQuantitytypeByPrimaryKey(quantitytype.getId());
	}

	@RequestMapping(value = "/restSaveQuantitytype", method = RequestMethod.PUT)
	@ResponseBody
	public Object restSaveQuantitytype(@RequestBody String quantitytypeJson) {
		Quantitytype quantitytype = new Gson().fromJson(quantitytypeJson, Quantitytype.class);
		appendReferences(quantitytype);
		CmiPsonService cmiPsonService = new CmiPsonService();
		quantitytypeService.saveQuantitytype(quantitytype);
		return JSONObject
				.parse(cmiPsonService.toJsonString(quantitytypeDAO.findQuantitytypeByPrimaryKey(quantitytype.getId()), 1));
	}

	@RequestMapping(value = "/restDeleteQuantitytype/{quantitytypeId}", method = RequestMethod.DELETE)
	@ResponseBody
	public void restDeleteQuantitytype(@PathVariable Integer quantitytypeId) {
		Quantitytype quantitytype = quantitytypeDAO.findQuantitytypeByPrimaryKey(quantitytypeId);
		quantitytypeService.deleteQuantitytype(quantitytype);
	}

	@RequestMapping(value = "/restConfirmDeleteQuantitytypes")
	@ResponseBody
	public Object restConfirmDeleteQuantitytypes(@RequestBody Set<Integer> deleteQuantitytypesIds) {
		Set<Quantitytype> deleteQuantitytypes = quantitytypeDAO.findQuantitytypesByIds(deleteQuantitytypesIds);
		Set<Quantitytype> referencedQuantitytypes = quantitytypeService.loadReferenceQuantitytypes(deleteQuantitytypes);
		deleteQuantitytypes.removeAll(referencedQuantitytypes);
		JSONObject jsonObject = new JSONObject();
		jsonObject.put("referencedEntitys", referencedQuantitytypes);
		jsonObject.put("deleteEntitys", deleteQuantitytypes);
		return JSONObject.parse(jsonObject.toJSONString());
	}

	@RequestMapping("/restDeleteQuantitytypes")
	@ResponseBody
	public Object restDeleteQuantitytypes(@RequestBody Set<Quantitytype> deleteQuantitytypes) {
		Iterator<Quantitytype> iterator = deleteQuantitytypes.iterator();
		while (iterator.hasNext()) {
			Quantitytype currentQuantitytype = iterator.next();
			quantitytypeService.deleteQuantitytype(currentQuantitytype);
		}
		JSONObject jsonObject = new JSONObject();
		jsonObject.put("url", "listQuantitytypes");
		return JSONObject.parse(jsonObject.toJSONString());
	}
	// loadself

	@RequestMapping(value = "/restLoadQuantitytype/{quantitytypeId}", method = RequestMethod.POST)
	@ResponseBody
	public Object restLoadQuantitytype(@PathVariable Integer quantitytypeId, @RequestBody CmiPagination cmiPagination) {
		CmiPsonService cmiPsonService = new CmiPsonService();
		return JSONObject.parse(
				cmiPsonService.toPsonString(quantitytypeDAO.findQuantitytypeByPrimaryKey(quantitytypeId), 2, cmiPagination));
	}
	// loadReferenceds
	// TODO loadReferencedsPson，这个方法有一些问题，待修复

	@RequestMapping(value = "/restLoadQuantitytypeEventquantitytypes/{quantitytypeId}/eventquantitytypes/{relatedeventquantitytypeId}", method = RequestMethod.POST)
	@ResponseBody
	public Object restLoadQuantitytypeEventquantitytypes(@PathVariable Integer quantitytypeId,
			@PathVariable Integer relatedeventquantitytypeId, @RequestBody CmiPagination cmiPagination) {
		Eventquantitytype eventquantitytype = eventquantitytypeDAO
				.findEventquantitytypeByPrimaryKey(relatedeventquantitytypeId, -1, -1);
		CmiPsonService cmiPsonService = new CmiPsonService();
		return JSONObject.parse(cmiPsonService.toPsonString(eventquantitytype, 2, cmiPagination));
	}

	public void appendReferences(Quantitytype quantitytype) {

		// 引用表不是纯联系表，引用数量大于或者等于2
		Set<Eventquantitytype> eventquantitytypesForQuantitytype = new HashSet<>();
		for (Eventquantitytype eventquantitytype_Quantitytype : quantitytype.getEventquantitytypesForQuantitytype()) {
			eventquantitytypesForQuantitytype.add(
					eventquantitytypeService.findEventquantitytypeByPrimaryKey(eventquantitytype_Quantitytype.getId()));
		}
		quantitytype.setEventquantitytypesForQuantitytype(eventquantitytypesForQuantitytype);
	}

	@RequestMapping(value = "/restGetQuantitytypeEventquantitytypes/{quantitytypeId}/eventquantitytypes", method = RequestMethod.POST)
	@ResponseBody
	public Object restGetQuantitytypeEventquantitytypes(@PathVariable Integer quantitytypeId,
			@RequestBody CmiPagination cmiPagination) {
		CmiPsonService cmiPsonService = new CmiPsonService();
		return JSONObject.parse(cmiPsonService.toPsonString(
				quantitytypeDAO.findQuantitytypeByPrimaryKey(quantitytypeId).getEventquantitytypesForQuantitytype(), 2,
				cmiPagination));
	}

	@RequestMapping(value = "/restListQuantitytypes", method = RequestMethod.GET)
	@ResponseBody
	public Object restListQuantitytypes() {
		return JSONObject.parse(cmiPsonService.toJsonString(quantitytypeService.loadQuantitytypes(), 2));
	}

	@RequestMapping(value = "/restListQuantitytypesPost", method = RequestMethod.POST)
	@ResponseBody
	public Object restListQuantitytypesPost(@RequestBody CmiPagination cmiPagination) {

		CmiPsonService cmiPsonService = new CmiPsonService();
		cmiPagination = quantitytypePaginationService.updateAppPagination(cmiPagination);
		int startResult = (cmiPagination.getCurrentPagination() - 1) * cmiPagination.getPaginationSize();

		Set<Quantitytype> quantitytypes = quantitytypeDAO.findAllQuantitytypes(startResult,
				cmiPagination.getPaginationSize());
		String quantitytypeString = cmiPsonService.toPsonString(quantitytypes, 2, cmiPagination);

		return JSONObject.parse(quantitytypeString);
	}

	@RequestMapping("/quantitytypeSelectBox")
	@ResponseBody
	public JSONObject quantitytypeSelectBox(@RequestParam(required = false) String searchTable,
			@RequestParam(required = false) Set<Integer> searchValue, // 杨宏宇2019-9-10：searchValue是在selectpage.js的616行定义，如果要修改searchValue的名称，1.可以修改在selectpage.js修改；2.可以
																		// @RequestParam(value="searchValue", required =
																		// false) Set<Integer> someName
			@RequestParam(required = false, defaultValue = "10") int paginationSize,
			@RequestParam(required = false, defaultValue = "1") int pageNumber,
			@RequestParam(value = "qWord[]", required = false) String queryword,
			@RequestParam(required = false) String selectItem) throws IOException {
		Set entitySet = null;
		Integer count = 0;

		// 初始化原始值

		if (searchValue != null) {
			switch (searchTable) {
			// 外键

			// 被引用键
			case "Eventquantitytype":
				entitySet = eventquantitytypeService.loadEventquantitytypesByIdSet(searchValue);
				break;
			}
			// 没有测试，深度需要多少？？？
			String jsonData = cmiPsonService.toJsonString(entitySet, 1);
			JSONArray jsonArray = new JSONArray();
			jsonArray = (JSONArray) JSON.parse((String) jsonData);

			JSONObject jsonObject = new JSONObject();
			jsonObject.put("list", jsonArray);
			jsonObject.put("totalRow", entitySet.size());
			return jsonObject;
		}

		// 不根据关键字进行搜索
		if (queryword == null || queryword.trim() == "") {
			switch (selectItem) {
			// 外键

			// 被引用键
			case "Eventquantitytype":
				entitySet = eventquantitytypeDAO.findAllEventquantitytypes((pageNumber - 1) * paginationSize,
						paginationSize);
				count = eventquantitytypeService.countEventquantitytypes();
				break;
			}
		} else {
			switch (selectItem) {
			// 外键

			// 被引用键
			case "Eventquantitytype":
				entitySet = eventquantitytypeDAO.findEventquantitytypeByNameContaining(queryword,
						(pageNumber - 1) * paginationSize, paginationSize);
				count = eventquantitytypeService.countEventquantitytypesByName(queryword);
				break;
			}
		}
		/**
		 * 将Json数据转换成jsonArray形式，需要通过pson方式进行转换，然后再转换成JsonArray。因为存在懒加载
		 * 没有直接使用CmiPsonService中的fromJson方法是因为，fromJson方法会将int类型的直接转换成double类型的数据，这个问题还没有解决
		 */
		// 没有测试，深度需要多少？？？
		String jsonData = cmiPsonService.toJsonString(entitySet, 1);
		JSONArray jsonArray = new JSONArray();
		jsonArray = (JSONArray) JSON.parse((String) jsonData);

		JSONObject jsonObject = new JSONObject();
		jsonObject.put("list", jsonArray);
		jsonObject.put("paginationSize", paginationSize);
		jsonObject.put("pageNumber", pageNumber);
		jsonObject.put("totalRow", count);
		jsonObject.put("totalPaginations",
				count % paginationSize == 0 ? count / paginationSize : count / paginationSize + 1);
		return jsonObject;
	}
}
